import { ref, onMounted } from "vue"
import { openFullScreenLoading, closeFullScreenLoading, initializeObjectValues, shallowCopy, toast } from './util'

export function useTableSearch(opt) {
  // 返回表格每行样式的回调函数，此处主要让偶数列底色变化
  const tableRowClassName = ({ row, rowIndex }) => {
    if (rowIndex % 2 == 0) {
      return "success-row"
    }
    return ""
  }

  const onSearch = () => {
    currentPage.value = 1
    getData()
  }


  const currentPage = ref(1)
  const tableData = ref(null)
  const totalCount = ref(0) // 分类总记录数
  const limit = ref(10) // 每页数据条数
  const getData = () => {
    const loading = openFullScreenLoading()
    opt.searchform.limit = limit.value
    opt.getTableList(currentPage.value, opt.searchform)
      .then((res) => {
        tableData.value = res.data.list
        totalCount.value = res.data.totalCount
        // console.log(tableData.value)
        if(opt.onGetDataSucceed && typeof opt.onGetDataSucceed == 'function') {
            opt.onGetDataSucceed(res)
        }
      })
      .finally(() => {
        closeFullScreenLoading(loading)
      })
  }

  onMounted(() => {
    currentPage.value = 1
    getData()
  })

  const onPageChange = (newPaegIndex) => {
    currentPage.value = newPaegIndex
    getData()
  }

  const onClearSearch = () => {
    initializeObjectValues(opt.searchform)
    currentPage.value = 1
    getData()
  }

  const headerHeight = ref(110) // height的高度
  const onMoreSearchChange = (params) => {
    if(params.SearchFormHeight) headerHeight.value = params.SearchFormHeight + 40
  }

  return {
    tableRowClassName,
    headerHeight,
    onSearch,
    onClearSearch,
    onMoreSearchChange,
    getData,
    onPageChange,
    currentPage,
    tableData,
    totalCount,
    limit
  }
}

export function useForm(opt) {
  const title = opt.title
  const formRef = ref(null)
  const drawerTitle = ref('')
  const drawerRef = ref(null)

/**
 * Deeply searches for an item in a tree structure by id
 * @param {Array} arr - The array to search through
 * @param {string|number} id - The id to search for
 * @returns {Object|null} The found item or null if not found
 */
const findItemDeep = (arr, id) => {
  // First try to find in current level
  const item = arr.find(i => i.id == id)
  if (item) return item
  
  // If not found, search in children
  for (const node of arr) {
    const children = node.child || node.children || []
    if (children.length > 0) {
      const found = findItemDeep(children, id)
      if (found) return found
    }
  }
  
  return null
}


  const onEdit = (row) => {
    const tableData = opt.tableData
    drawerRef.value.open()
    drawerTitle.value = "编辑" + title
    let item = findItemDeep(tableData.value, row.id)
    shallowCopy(item, opt.form)
    // 初始化数据
    if(opt.formDataInit) opt.formDataInit(opt.form)
  }



  const onAdd = () => {
      drawerRef.value.open()
      drawerTitle.value = "新增" + title
      clearForm()
      // 初始化数据
      if(opt.formDataInit) opt.formDataInit(opt.form)
  }

  const onDelete = (row) => {
    opt.delete(row.id).then(res => {
          toast("删除"+ title +"成功")
          opt.getData()
      })
  }

  // 多选处理
  // 定义选中的内容集合
  const multipleSelection = ref([])
  // 多选处理
  const onSelectionChange = (val) => {
      multipleSelection.value = val
  }

  // 批量删除
  const onMultiDelete = () => {
    if(multipleSelection.value.length <= 0) {
      toast("请先选择要删除的数据，再点击批量删除按钮！",'info')
    } else {
      const ids = []
      multipleSelection.value.forEach(el => {
          ids.push(el.id)
      })
      opt.multiDelte(ids).then(res => {
          toast("批量删除成功")
          opt.getData()
      })
    }
  }

  // 批量设置
  const onMultiSet = (params) => {
    if(multipleSelection.value.length <= 0) {
      toast("请先选择要操作的数据，再点击此按钮！",'info')
    } else {
      const ids = []
      multipleSelection.value.forEach(el => {
          ids.push(el.id)
      })
      if(opt.multiSet && typeof opt.multiSet == 'function') {
        opt.multiSet(ids, params)
      }
    }
  }

  const onStatusChange = (row) => {
    const loading = openFullScreenLoading()
    // console.log('row=', row)
    if(row.id != null && row.id > 0) {
      opt.updateStatus(row.id, row.status).then(res => {
        toast("修改"+ title +"状态成功")
       }).finally(() => {
        closeFullScreenLoading(loading)
      })
    }
}


  const onSubmit = () => {
      formRef.value.validate(async valid => {
          if (!valid) {
              return false
          }
          drawerRef.value.showLoading()

          // 在提交按钮前执行
          if(opt.beforeSubmit != null) {
            opt.beforeSubmit(opt.form)
          }

          if (opt.form.id > 0) {
              opt.update(opt.form).then(res => {
                  toast("修改" + title + "成功")
                  opt.getData()
              }).catch(err => {
                  // do nothing
              }).finally(() => {
                  clearFormAndClose()
              })
          } else {
              opt.add(opt.form).then(res => {
                  toast("新增" + title + "成功")
                  opt.getData()
              }).catch(err => {
                  // do nothing
              }).finally(() => {
                  clearFormAndClose()
              })
          }
      })
  }

  // 新增、修改完毕后对form进行清空处理
  const clearFormAndClose = () => {
      drawerRef.value.hideLoading()
      drawerRef.value.close()
      clearForm()
  }

  const clearForm = () => {
      initializeObjectValues(opt.form)
  }

  return {
    formRef,
    drawerRef,
    drawerTitle,
    onAdd,
    onEdit,
    onDelete,
    onSubmit,
    onStatusChange,
    clearFormAndClose,
    clearForm,
    onMultiDelete,
    onMultiSet,
    onSelectionChange
  }
}
